package mat;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.apache.log4j.Logger;

public class CsvMatrixReader
{
	private Logger log;
	private String filePath;
	private int rows;
	private int cols;
	private String delimiter;
	private Mat matrix;
	private String name;

	private long retryIfExistsInSec = 30;
	private long maxRetryInSec = 3600;
	
	public CsvMatrixReader(String name, String filePath, int rows, int cols, String delimiter)
	{
		this.log = Logger.getLogger(this.getClass());
		this.name = name;
		this.filePath = filePath;
		this.rows = rows;
		this.cols = cols;
		this.delimiter=delimiter;
	}
	

	public void process() throws IOException, InterruptedException
	{
		long t0 = System.currentTimeMillis();
		
		File file;
		
		long t = System.currentTimeMillis() + maxRetryInSec * 1000;
		while (t > System.currentTimeMillis())
		{
			if (canReadAny())
				break;
			
			log.info("Wait for " + filePath + "...");
			Thread.sleep(retryIfExistsInSec * 1000);
		}
		
		file = new File(filePath);
		if (file.exists())
		{
			processFlatFile(file);
		}
		
		long t1 = System.currentTimeMillis();
		log.info("Processed " + file.getName() + ", " + (t1 -t0) + "ms");
	}
	
	// FIXME, see FileParser
	private boolean canReadAny() throws IOException
	{
		MultiProtocolFile mpf = new MultiProtocolFile(filePath);
		return 	mpf.exists();		

	}

	
	private void processFlatFile(File file) throws IOException
	{
		log.info("Processing " + file.getName());
		FileReader fr = new FileReader(file);
	    BufferedReader bufRdr = new BufferedReader(fr);
		try
		{
			readFully(bufRdr);
		}
		finally
		{
			if (bufRdr != null)
				bufRdr.close();
		}
	}
	
	
	private void readFully(BufferedReader bufRdr) throws IOException
	{

		double[][] data = new double[rows][cols];
		String line = null;
		int row = 0;
			while((line = bufRdr.readLine()) != null)
			{
				String[] st = line.split(delimiter);
				for(int col=0;col<st.length;col++)
				{
					data[row][col] = Double.parseDouble(st[col]);
					
				}
				row++;
			}
		matrix = new Mat(name, data);
	}


	public Mat getMatrix()
	{
		return matrix;
	}
	
	

}



